package com.augmentum.login.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;

import com.augmentum.login.AppContent;
import com.augmentum.login.Constants;
import com.augmentum.login.model.User;

public class AppContentFilter implements Filter {
    private final Logger logger = Logger.getLogger(AppContentFilter.class);
    @Override
    public void destroy() {
        // empty
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest)request;
        HttpServletResponse httpResponse = (HttpServletResponse)response;
        AppContent appContent = AppContent.getAppContent();
        User user = (User)httpRequest.getSession().getAttribute(Constants.USER);

        HttpSession session = httpRequest.getSession();
        appContent.addObject(Constants.SESSION, session);
        appContent.addObject(Constants.USER, user);
        appContent.addObject(Constants.RESPONSE, httpResponse);
        AppContent.setContentPath(httpRequest.getContextPath());
        try {
            chain.doFilter(request, response);
        } catch (IOException ioe) {
            logger.warn(ioe);
            throw ioe;
        } catch (ServletException se) {
            logger.warn(se);
            throw se;
        } catch (RuntimeException re) {
            logger.warn(re);
            throw re;
        } finally {
            appContent.clearMap();
        }
    }

    @Override
    public void init(FilterConfig fConfig) throws ServletException {
        // empty
    }
}
